package com.ruoyi.develop.payApply.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSalebuyall.domain.GoodsSalebuyall;
import com.ruoyi.develop.goodsSalebuyall.mapper.GoodsSalebuyallMapper;
import com.ruoyi.develop.lnZhaobiao.domain.LnZhaobiao;
import com.ruoyi.develop.lnZhaobiao.service.ILnZhaobiaoService;
import com.ruoyi.develop.lvBuy.domain.LvBuy;
import com.ruoyi.develop.lvBuy.mapper.LvBuyMapper;
import com.ruoyi.develop.orderIronRecordBuy.domain.OrderIronRecordBuy;
import com.ruoyi.develop.payApplyBuy.domain.PayApplyBuy;
import com.ruoyi.develop.payApplyBuy.mapper.PayApplyBuyMapper;
import com.ruoyi.develop.payApplyBuyDetail.domain.PayApplyBuyDetail;
import com.ruoyi.develop.payApplyBuyDetail.mapper.PayApplyBuyDetailMapper;
import com.ruoyi.develop.payApplyBuyDetail.service.IPayApplyBuyDetailService;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.payApply.mapper.PayApplyMapper;
import com.ruoyi.develop.payApply.domain.PayApply;
import com.ruoyi.develop.payApply.service.IPayApplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 付款申请单Service业务层处理
 *
 * @author lmm
 * @date 2024-10-09
 */
@Service
public class PayApplyServiceImpl implements IPayApplyService {
    @Resource
    private PayApplyMapper payApplyMapper;
    @Resource
    private LvBuyMapper lvBuyMapper;
    @Resource
    private PayApplyBuyMapper payApplyBuyMapper;
    @Resource
    private GoodsSalebuyallMapper goodsSalebuyallMapper;
    @Resource
    private IPayApplyBuyDetailService payApplyBuyDetailService;
    @Resource
    private ILnZhaobiaoService lnZhaobiaoService;



    /**
     * 查询付款申请单
     *
     * @param id 付款申请单主键
     * @return 付款申请单
     */
    @Override
    public PayApply selectById(String id) {
        PayApplyBuy payApplyBuy = new PayApplyBuy();
        payApplyBuy.setApplyId(id);
        List<PayApplyBuy> payApplyBuyList = payApplyBuyMapper.selectList(payApplyBuy);
        PayApply payApply = payApplyMapper.selectById(id);
        payApply.setPayApplyBuyList(payApplyBuyList);

        PayApplyBuyDetail payApplyBuyDetail = new PayApplyBuyDetail();
        payApplyBuyDetail.setPayApplyId(id);
        List<PayApplyBuyDetail> payApplyBuyDetailList = payApplyBuyDetailService.selectList(payApplyBuyDetail);
        payApply.setPayApplyBuyDetailList(payApplyBuyDetailList);

        return payApply;
    }

    /**
     * 查询付款申请单列表
     *
     * @param entity 付款申请单
     * @return 付款申请单
     */
    @Override
    public List<PayApply> selectList(PayApply entity) {
        return payApplyMapper.selectList(entity);
    }

    @Override
    public List<PayApply> selectListByBuy(PayApply entity) {
        return payApplyMapper.selectListByBuy(entity);
    }


    /**
     * 新增付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int insert(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        if(StringUtils.isBlank(entity.getInvoicePhoto())){
            entity.setIsInvoice(BusinessConstants.STATUS_NO);
        }else{
            entity.setIsInvoice(BusinessConstants.STATUS_YES);
        }
        entity.setNos(getMaxNos());
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return payApplyMapper.insert(entity);
    }

    /**
     * 修改付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int update(PayApply entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        if(StringUtils.isBlank(entity.getInvoicePhoto())){
            entity.setIsInvoice(BusinessConstants.STATUS_NO);
        }else{
            entity.setIsInvoice(BusinessConstants.STATUS_YES);
        }
        return payApplyMapper.update(entity);
    }

    /**
     * 批量删除付款申请单
     *
     * @param ids 需要删除的付款申请单主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return payApplyMapper.deleteByIds(ids);
    }

    /**
     * 删除付款申请单信息
     *
     * @param id 付款申请单主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return payApplyMapper.deleteById(id);
    }

    /**
     * 新增   定金付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int addForDeposit(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        // 更新 采购单状态 申请付定金
        String buyId = entity.getBuyId();
        LvBuy buy = lvBuyMapper.selectById(buyId);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setType(BusinessConstants.PAY_APPLY_TYPE_DEPOSIT);
        entity.setCategory(BusinessConstants.PAY_APPLY_CATEGORY_BUY_COMMON);
        entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        entity.setSupplierName(buy.getSupplierName());
        entity.setBankName(buy.getBankName());
        entity.setAccountNo(buy.getAccountNo());
        entity.setBankNo(buy.getBankNo());
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        int i =  payApplyMapper.insert(entity);
        buy.setPayApplyTotalMoney(buy.getPayApplyTotalMoney().add(entity.getTotalMoney()));
        buy.setPayApplyRemainMoney(buy.getPayApplyRemainMoney().subtract(entity.getTotalMoney()));
        buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_APPLY);
        lvBuyMapper.update(buy);

        List<PayApplyBuyDetail> payApplyBuyDetailList =  entity.getPayApplyBuyDetailList();
        for (PayApplyBuyDetail payApplyBuyDetail : payApplyBuyDetailList) {
            payApplyBuyDetail.setPayApplyId(entity.getId());
            GoodsSalebuyall goodsSalebuyall = goodsSalebuyallMapper.selectById(payApplyBuyDetail.getBuyDetailId());
            goodsSalebuyall.setApplyMoney(goodsSalebuyall.getApplyMoney().add(payApplyBuyDetail.getMoney()));
            goodsSalebuyall.setApplyRemain(goodsSalebuyall.getApplyRemain().subtract(payApplyBuyDetail.getMoney()));
            goodsSalebuyallMapper.update(goodsSalebuyall);
            payApplyBuyDetailService.insert(payApplyBuyDetail);
        }

        return i;
    }



    /**
     * 新增 运费 付款申请单
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int addForShippingFee(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        // 更新 采购单状态 申请 付运费
        String buyId = entity.getBuyId();
        LvBuy buy = lvBuyMapper.selectById(buyId);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setType(BusinessConstants.PAY_APPLY_TYPE_ALL);
        entity.setCategory(BusinessConstants.PAY_APPLY_CATEGORY_SHIPPING);
        entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        int i =  payApplyMapper.insert(entity);
        buy.setShippingStatus(BusinessConstants.BUY_PAY_SHIPPING_APPLY);
        lvBuyMapper.update(buy);

        List<PayApplyBuyDetail> payApplyBuyDetailList =  entity.getPayApplyBuyDetailList();
        for (PayApplyBuyDetail payApplyBuyDetail : payApplyBuyDetailList) {
            payApplyBuyDetail.setPayApplyId(entity.getId());
            payApplyBuyDetailService.insert(payApplyBuyDetail);
        }
        return i;
    }



    /**
     * 新增 招标 付款申请单
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int addForBid(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        // 更新 采购单状态 申请 付运费
        String bidId = entity.getBidId();
        LnZhaobiao bid = lnZhaobiaoService.selectById(bidId);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setType(BusinessConstants.PAY_APPLY_TYPE_ALL);
        entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        entity.setAssessStatus(BusinessConstants.PAY_APPLY_ASSESS_STATUS_AUDIT_PASS);
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        int i =  payApplyMapper.insert(entity);
        if (BusinessConstants.PAY_APPLY_CATEGORY_BOND.equals(entity.getCategory())) {
            // 如果是保证金
            bid.setBondStatus(BusinessConstants.STATUS_YES);
        }
        if (BusinessConstants.PAY_APPLY_CATEGORY_SERVICE.equals(entity.getCategory())) {
            // 如果是保证金
            bid.setServiceStatus(BusinessConstants.STATUS_YES);
        }
        if (BusinessConstants.PAY_APPLY_CATEGORY_BOOK.equals(entity.getCategory())) {
            // 如果是保证金
            bid.setBookStatus(BusinessConstants.STATUS_YES);
        }
        lnZhaobiaoService.update(bid);
        return i;
    }


    public String getMaxNos(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = payApplyMapper.selectMaxCode(today);
        if(StringUtils.isNotBlank(codeMaxString)){
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString)+1+"";
        }else{
            codeMaxString = today+"0001";
        }
        return codeMaxString;
    }


    /**
     * 新增   材料 尾款 付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int addForUnion(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        String buyId = entity.getBuyId();
        LvBuy buy = lvBuyMapper.selectById(buyId);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());

        if(BusinessConstants.STATUS_YES.equals(buy.getDepositMerge())){
            if((buy.getMoney().add(buy.getShippingFee())).compareTo(entity.getTotalMoney())==0){
                entity.setType(BusinessConstants.PAY_APPLY_TYPE_ALL);
                entity.setShippingFee(buy.getShippingFee());
                buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_APPLY);
            }else{
                entity.setType(BusinessConstants.PAY_APPLY_TYPE_PART);
                buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PART);
            }
        }

        if(BusinessConstants.STATUS_NO.equals(buy.getDepositMerge())){
            if(buy.getMoney().compareTo(entity.getTotalMoney())==0){
                entity.setShippingFee(BigDecimal.ZERO);
                entity.setType(BusinessConstants.PAY_APPLY_TYPE_ALL);
                buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_APPLY);
            }else{
                entity.setType(BusinessConstants.PAY_APPLY_TYPE_PART);
                buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PART);
            }
        }

        entity.setSupplierName(buy.getSupplierName());
        entity.setBankName(buy.getBankName());
        entity.setAccountNo(buy.getAccountNo());
        entity.setBankNo(buy.getBankNo());
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        entity.setCategory(BusinessConstants.PAY_APPLY_CATEGORY_BUY_COMMON);
        // 判断是付款还是退款
        if(entity.getTotalMoney().compareTo(BigDecimal.ZERO)>0){
            entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        }else{
            entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_REFUND);
        }

        int i =  payApplyMapper.insert(entity);
        buy.setPayApplyTotalMoney(buy.getPayApplyTotalMoney().add(entity.getTotalMoney()));
        buy.setPayApplyRemainMoney(buy.getPayApplyRemainMoney().subtract(entity.getTotalMoney()));

        lvBuyMapper.update(buy);
        List<PayApplyBuyDetail> payApplyBuyDetailList =  entity.getPayApplyBuyDetailList();
        for (PayApplyBuyDetail payApplyBuyDetail : payApplyBuyDetailList) {
            payApplyBuyDetail.setPayApplyId(entity.getId());
            GoodsSalebuyall goodsSalebuyall = goodsSalebuyallMapper.selectById(payApplyBuyDetail.getBuyDetailId());
            goodsSalebuyall.setApplyMoney(goodsSalebuyall.getApplyMoney().add(payApplyBuyDetail.getMoney()));
            goodsSalebuyall.setApplyRemain(goodsSalebuyall.getApplyRemain().subtract(payApplyBuyDetail.getMoney()));
            goodsSalebuyallMapper.update(goodsSalebuyall);
            payApplyBuyDetailService.insert(payApplyBuyDetail);
        }
        return i;
    }



    /**
     * 新增   铁件 付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    public int addForIron(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        String buyId = entity.getBuyId();
        LvBuy buy = lvBuyMapper.selectById(buyId);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setSupplierName(buy.getSupplierName());
        entity.setBankName(buy.getBankName());
        entity.setAccountNo(buy.getAccountNo());
        entity.setBankNo(buy.getBankNo());
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        entity.setBuyNos(buy.getNos());
        entity.setType(BusinessConstants.PAY_APPLY_TYPE_ALL);
        entity.setCategory(BusinessConstants.PAY_APPLY_CATEGORY_BUY_IRON);
        entity.setAssessStatus(BusinessConstants.PAY_APPLY_ASSESS_STATUS_UN);
        entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        int i =  payApplyMapper.insert(entity);
        buy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_APPLY);
        buy.setPayApplyTotalMoney(buy.getPayApplyTotalMoney().add(entity.getTotalMoney()));
        lvBuyMapper.update(buy);
        return i;
    }


    /**
     * 新增 合并付款 付款申请单
     *
     * @param entity 付款申请单
     * @return 结果
     */
    @Override
    @Transactional
    public int addForBuyList(PayApply entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        String[] buyIds = entity.getBuyId().split(",");
        LvBuy buy = lvBuyMapper.selectById(buyIds[0]);
        entity.setSupplierName(buy.getSupplierName());
        entity.setSupplierId(buy.getSupplierId());
        entity.setBankName(buy.getBankName());
        entity.setAccountNo(buy.getAccountNo());
        entity.setBuyId(entity.getBuyId());
        entity.setType(BusinessConstants.PAY_APPLY_TYPE_SUM);
        entity.setCategory(BusinessConstants.PAY_APPLY_CATEGORY_BUY_COMMON);
        entity.setTransactionType(BusinessConstants.PAY_APPLY_TRANSACTION_TYPE_PAY);
        entity.setRemainMoney(entity.getTotalMoney());
        entity.setNos(getMaxNos());
        entity.setCreateTime(new Date());
        entity.setCreateBy(SecurityUtils.getUsername());
        List<LvBuy> lvBuyList=entity.getLvBuyList();
        int i =  payApplyMapper.insert(entity);
        StringBuffer buyNos = new StringBuffer();
        for (LvBuy lvBuy : lvBuyList) {
            // 先只考虑 合并付款 付全款的情况 也要 考虑 分定金和尾款情况
            List<PayApplyBuyDetail> payApplyBuyDetailList =  selectPayApplyBuyDetailList(entity.getId(),lvBuy.getId(),lvBuy.getApplyMoneyTemp());
            for (PayApplyBuyDetail payApplyBuyDetail:payApplyBuyDetailList){
                payApplyBuyDetailService.insert(payApplyBuyDetail);
                GoodsSalebuyall goodsSalebuyall = payApplyBuyDetail.getBuyDetail();
//                goodsSalebuyall.setApplyRemain(goodsSalebuyall.getApplyRemain().subtract(payApplyBuyDetail.getMoney()));
                goodsSalebuyall.setApplyMoney(goodsSalebuyall.getApplyMoney().add(payApplyBuyDetail.getMoney()));
                goodsSalebuyallMapper.update(goodsSalebuyall);
            }

            if(lvBuy.getPayApplyRemainMoney().compareTo(lvBuy.getApplyMoneyTemp())==0){
                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_ALL_APPLY);
            }else{
                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PART);
            }

            buyNos.append(lvBuy.getNos() + ",");
            lvBuy.setFpState(BusinessConstants.TAX_STATUS_1);
            lvBuy.setKaipiao(lvBuy.getKaipiao().add(lvBuy.getShengyukp()));
            lvBuy.setShengyukp(lvBuy.getShengyukp().subtract(lvBuy.getShengyukp()));
            lvBuy.setPayApplyTotalMoney(lvBuy.getPayApplyTotalMoney().add(lvBuy.getApplyMoneyTemp()));
            lvBuy.setPayApplyRemainMoney(lvBuy.getPayApplyRemainMoney().subtract(lvBuy.getApplyMoneyTemp()));
            lvBuyMapper.update(lvBuy);
            if(lvBuy.getShengyukp().compareTo(BigDecimal.ZERO)==0){
                lvBuy.setFpState(BusinessConstants.TAX_STATUS_2);
                lvBuyMapper.update(lvBuy);
            }
            PayApplyBuy payApplyBuy = new PayApplyBuy();
            payApplyBuy.setId(IdUtils.fastSimpleUUID());
            payApplyBuy.setApplyId(entity.getId());
            payApplyBuy.setBuyId(lvBuy.getId());
            payApplyBuy.setCreateTime(DateUtils.getNowDate());
            payApplyBuy.setCreateBy(SecurityUtils.getUserId());
            payApplyBuy.setKpMoney(lvBuy.getShengyukp());
            payApplyBuy.setApplyMoney(lvBuy.getApplyMoneyTemp());
            payApplyBuyMapper.insert(payApplyBuy);

        }
        entity.setBuyNos(buyNos.toString());
        payApplyMapper.update(entity);
        return i;
    }

    @Override
    public List<PayApplyBuyDetail> selectPayApplyBuyDetailList(String payApplyId,String buyId,BigDecimal totalMoney) {
        GoodsSalebuyall goodsSalebuyall = new GoodsSalebuyall();
        goodsSalebuyall.setMainId(buyId);
        List<GoodsSalebuyall> list = goodsSalebuyallMapper.selectList(goodsSalebuyall);
        // 根据申请付款总金额 totalMoney 依次从 list 减去
        List<PayApplyBuyDetail> payApplyBuyDetailList = new ArrayList<>();
        for (GoodsSalebuyall buyDetail : list) {
            PayApplyBuyDetail payApplyBuyDetail = new PayApplyBuyDetail();
            payApplyBuyDetail.setBuyId(buyDetail.getMainId());
            payApplyBuyDetail.setBuyDetailId(buyDetail.getId());
            payApplyBuyDetail.setGoodsId(buyDetail.getGoodsId());
            payApplyBuyDetail.setGoodsName(buyDetail.getGoodsName());
            payApplyBuyDetail.setGoodsModel(buyDetail.getGoodModel());
            payApplyBuyDetail.setGoodsCode(buyDetail.getGoodsCode());
            payApplyBuyDetail.setPayApplyId(payApplyId);
            payApplyBuyDetail.setBuyDetail(buyDetail);
            payApplyBuyDetail.setAmount(buyDetail.getShengyu());
            if(totalMoney.compareTo(buyDetail.getApplyRemain())>0){
                totalMoney = totalMoney.subtract(buyDetail.getApplyRemain());
                payApplyBuyDetail.setMoney(buyDetail.getApplyRemain());
                buyDetail.setApplyRemain(BigDecimal.ZERO);
            }else{
                payApplyBuyDetail.setMoney(totalMoney);
                totalMoney = BigDecimal.ZERO;
                buyDetail.setApplyRemain(buyDetail.getApplyRemain().subtract(totalMoney));
            }
            payApplyBuyDetail.setPayRemain(payApplyBuyDetail.getMoney());
            payApplyBuyDetail.setPayMoney(BigDecimal.ZERO);
            payApplyBuyDetail.setRemark(buyDetail.getRemark());
            payApplyBuyDetailList.add(payApplyBuyDetail);
        }
        return payApplyBuyDetailList;
    }





}
